package config

import (
	"log"
	"os"

	"github.com/joho/godotenv"
)

type Config struct {
	Port        string
	DatabaseURL string
	Environment string
	JWTSecret   string
	DBType      string
	// 添加OpenIM配置
	OpenIMAPIURL    string
	OpenIMWSURL     string
	OpenIMSecret    string
	OpenIMAdminUser string
	OpenIMAdminPass string
	// 添加OpenIM管理端URL配置
	OpenIMAdminURL string
	OpenIMChatURL  string
}

func Load() *Config {
	// 加载.env文件
	if err := godotenv.Load(); err != nil {
		log.Println("No .env file found, using environment variables")
	}

	// 默认使用SQLite3数据库
	defaultDatabaseURL := "./payment_system.db"

	config := &Config{
		Port:        getEnv("PORT", "8080"),
		DatabaseURL: getEnv("DATABASE_URL", defaultDatabaseURL),
		Environment: getEnv("ENVIRONMENT", "development"),
		JWTSecret:   getEnv("JWT_SECRET", "your-default-secret-key"),
		// 添加OpenIM配置 - 使用真实的OpenIM服务器地址
		OpenIMAPIURL:    getEnv("OPENIM_API_URL", "http://49.232.89.148:10008"),
		OpenIMWSURL:     getEnv("OPENIM_WS_URL", "ws://49.232.89.148:10001"),
		OpenIMSecret:    getEnv("OPENIM_SECRET", "openIM123"),
		OpenIMAdminUser: getEnv("OPENIM_ADMIN_USER", "imAdmin1"),
		OpenIMAdminPass: getEnv("OPENIM_ADMIN_PASS", "openIM123"),
		// 添加OpenIM管理端URL配置
		OpenIMAdminURL: getEnv("OPENIM_ADMIN_URL", "http://49.232.89.148:10002"),
		OpenIMChatURL:  getEnv("OPENIM_CHAT_URL", "http://49.232.89.148:10009"),
	}

	// 设置数据库类型
	if getEnv("DB_TYPE", "") == "mysql" {
		config.DBType = "mysql"
		if config.DatabaseURL == defaultDatabaseURL {
			// 如果没有设置DATABASE_URL但指定了mysql，使用默认mysql配置
			config.DatabaseURL = "root:password@tcp(localhost:3306)/payment_system?charset=utf8mb4&parseTime=True&loc=Local"
		}
	} else {
		config.DBType = "sqlite"
	}

	return config
}

func getEnv(key, defaultValue string) string {
	if value := os.Getenv(key); value != "" {
		return value
	}
	return defaultValue
}
